package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.YunAlbumWallAdapter2;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.view.SpacesItemDecoration;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.HeaderSpanSizeLookup;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jp.wasabeef.recyclerview.animators.ScaleInAnimator;

public class YunAlbumActivity2 extends BaseActivity implements View.OnClickListener {
    private TextView mPreview;                        // 预览
    private TextView mUpLoad;                            // 上传
    private RecyclerView rv_home_album;              // 列表视图
    private YunAlbumWallAdapter2 mAdapter;                   // 适配器
    private LinkedList<YNPhoto> mPhotoDatas;                // 照片墙数据
    private boolean isBottom;
    private WrapContentGridLayoutManager mGridLayoutManager;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    public static Map<Integer, Boolean> checkPos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        mPhotoDatas = new LinkedList<>();
        setContentView(R.layout.yn_activity_yun_album);
        checkPos = new HashMap<Integer, Boolean>();
        initView();
        noticeServiceInit();
    }

    // 通知后台加载数据
    private void noticeServiceInit() {
        Intent mIntent = new Intent(YunAlbumActivity2.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
        mIntent.putExtra(ACTIONs.aLoadId, 0);
        startService(mIntent);
    }

    private void initView() {
        mUpLoad = (TextView) findViewById(R.id.btn_album_manage_sure);
        mPreview = (TextView) findViewById(R.id.btn_album_manage_preview);
        findViewById(R.id.timegood_back).setOnClickListener(this);
        mUpLoad.setOnClickListener(this);
        mPreview.setOnClickListener(this);
        rv_home_album = (RecyclerView) findViewById(R.id.rv_yun_album);
        rv_home_album.setItemAnimator(new ScaleInAnimator(new OvershootInterpolator(1f)));
        rv_home_album.getItemAnimator().setAddDuration(500);
        rv_home_album.getItemAnimator().setRemoveDuration(500);
        rv_home_album.getItemAnimator().setMoveDuration(500);
        rv_home_album.getItemAnimator().setChangeDuration(500);
        mAdapter = new YunAlbumWallAdapter2(YunAlbumActivity2.this, mPhotoDatas, YunAlbumActivity2.this);
        rv_home_album.setHasFixedSize(true);
        SpacesItemDecoration decoration = new SpacesItemDecoration(3);
        rv_home_album.addItemDecoration(decoration);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        rv_home_album.setAdapter(mYNRecyclerViewAdapter);
        mGridLayoutManager = new WrapContentGridLayoutManager(YunAlbumActivity2.this, 3);
        mGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((YNRecyclerViewAdapter) rv_home_album.getAdapter(), mGridLayoutManager.getSpanCount()));
        rv_home_album.setLayoutManager(mGridLayoutManager);
        rv_home_album.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                if (isBottom) {
                    return;
                }
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_home_album);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                RecyclerViewStateUtils.setFooterViewState(YunAlbumActivity2.this, rv_home_album, 30, LoadingFooter.State.Loading, null);
                rv_home_album.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadStatus(false, CommonConstants.YNS_SIGN_LOAD);
                    }
                }, 1000);
            }
        });
    }

    private void loadStatus(boolean isTop, String type) {
        // 通知后台加载数据
        Intent mIntent = new Intent(YunAlbumActivity2.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aNeedType, type);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mAdapter.getIdByDirection(isTop));
        startService(mIntent);
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }


    public void setSureCount(int totals) {
        mUpLoad.setText("上传" + switchSure(totals));
        mPreview.setText("预览" + switchSure(totals));
    }

//    // 开始剪切过程
//    private void beginCrop(Uri source) {
//        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
//        File cropFile = new File(mTempDir, fileName);
//        Uri outputUri = Uri.fromFile(cropFile);
//        new Crop(source).output(outputUri).asX345Y359().setCropType(false).start(this);
//    }

    private String imagelocal;

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            SelectedImg.mSelectedImage.clear();
            imagelocal = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            SelectedImg.mSelectedImage.add(imagelocal);
            intent2Activity(VoiceCardEditActivity.class);
            //   TimeGoodsAlbumActivity.mTimeGoodsAlbumActivity.finish();
            finish();
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            default:
                break;
        }
    }

    ProgressDialog mProgressDialog;
    Handler downloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                mProgressDialog.dismiss();
                Uri uri = Uri.parse("file://" + localPath);
//                beginCrop(uri);
                if (MainActivity.goodsid == 3) {
                    Intent intent = new Intent(YunAlbumActivity2.this, TimeGoodsDrawActivity.class);
                    intent.putExtra("goodsPic", localPath);
                    startActivity(intent);
                    finish();
                } else if (MainActivity.goodsid == 4) {
                    Intent intent = new Intent(YunAlbumActivity2.this, TimeGoodsJointActivity.class);
                    intent.putExtra("goodsPic", localPath);
                    startActivity(intent);
                    finish();
                }
            }
        }
    };

    String localPath;

    @Override
    public void onClick(View v) {
        List<String> list = SelectedImg.mSelectedImage;
        switch (v.getId()) {
            case R.id.btn_album_manage_sure:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再上传");
                    return;
                }
                final String path = list.get(0);
                mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
                Long tsLong = System.currentTimeMillis() / 1000;
                final String ts = "yn_" + tsLong.toString() + ".png";
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
                if (!(file.mkdir() || file.isDirectory())) {
                    file.mkdirs();
                }
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            URL url1 = new URL(path);
                            // 打开链接
                            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                            conn.setConnectTimeout(5000);
                            conn.setRequestMethod("GET");
                            int code = conn.getResponseCode();
                            if (code == 200) {
                                InputStream is = conn.getInputStream();
                                localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yinian/YiNian" + ts;
                                File f = new File(new File(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/", "yinian/YiNian" + ts);
                                if (f.exists()) {
                                    f.delete();
                                }
                                FileOutputStream fos = new FileOutputStream(f);
                                int len = 0;
                                byte[] buff = new byte[1024];
                                while ((len = is.read(buff)) != -1) {
                                    fos.write(buff, 0, len);
                                }
                                is.close();
                                fos.close();
                                downloadHandler.sendEmptyMessage(2);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.btn_album_manage_preview:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再预览");
                    return;
                }
                Intent toPreview = new Intent(this, PreviewActivity.class);
                startActivity(toPreview);
                break;
            case R.id.timegood_back:
                finish();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setSureCount(SelectedImg.mSelectedImage.size());
        // mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    setSureCount(SelectedImg.mSelectedImage.size());
                    break;
                case ACTIONs.actionWallUpdate:
                    List<YNPhoto> photoList = (List<YNPhoto>) intent.getSerializableExtra(ACTIONs.aAddData);
                    String direction = intent.getStringExtra(ACTIONs.aAddDirection);
                    updateView(photoList, direction);
                    break;
            }
        }
    };

    private void updateView(List<YNPhoto> photoList, String direction) {
        switch (direction) {
            case ACTIONs.aAddTop:
                mAdapter.addItemsFromTop(photoList);
//                rv_home_album.scrollToPosition(0);
                for (int i = 0; i < photoList.size(); i++) {
                    checkPos.put(i, false);
                }
                break;
            case ACTIONs.aAddBottom:
                mAdapter.addItemsFromBottom(photoList);
                if (photoList.size() == 0) {
                    isBottom = true;
                    RecyclerViewStateUtils.setFooterViewState(YunAlbumActivity2.this, rv_home_album, 30, LoadingFooter.State.TheEnd, null);
                } else {
                    RecyclerViewStateUtils.setFooterViewState(rv_home_album, LoadingFooter.State.Normal);
                }
                break;
        }
    }

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionWallUpdate);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
